package com.qf.ticketredis.controller;

import com.qf.ticketredis.pojo.Ticket;
import com.qf.ticketredis.service.TicketService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketService ticketService;

	@Autowired
	private CuratorZkTemplate zkTemplate;

	private static final String LOCK_PREFIX = "/LOCK:";

    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id) throws InterruptedException {

		InterProcessLock lock = zkTemplate.getSharedReentrantLock(LOCK_PREFIX + id);

		while (true){
			try {
				//加锁
				lock.acquire();
				//查询id对应的票务信息，是否有剩余票
				Ticket ticket = ticketService.getById(id);
				Integer count = ticket.getCount();
				if (count > 0) {
					System.out.println("正在卖出第" + count + "张票");
					//模拟卖票时间
					Thread.sleep(1000);

					count = count - 1;

					//重新更新数据库的票务信息
					ticket.setCount(count);
					ticketService.updateById(ticket);
					System.out.println("剩余票数为：" + count);
				} else {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				//释放锁
				try {
					lock.release();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
        }
    }
}
